/**
 * CreateTaskModal Component
 * 创建采集任务模态框
 * Features: 数据源选择、采集类型选择、表单验证
 */

import React from 'react'
import { Modal, Form, Select, Radio, message } from 'antd'
import type { DataSource } from '@/services/models/types'
import { TaskType } from '@/services/models/types'
import { useDataSourceList } from '@/hooks/useDataSource'
import { useCreateCollectionTask } from '@/hooks/useCollectionTask'

interface CreateTaskModalProps {
  open: boolean
  onClose: () => void
}

interface CreateTaskFormValues {
  datasourceId: number
  taskType: TaskType
}

export const CreateTaskModal: React.FC<CreateTaskModalProps> = ({ open, onClose }) => {
  const [form] = Form.useForm<CreateTaskFormValues>()

  // 查询数据源列表(仅显示已启用的)
  const { data: datasourcesData, isLoading: loadingDatasources } = useDataSourceList(
    { enabled: true },
    { enabled: open } // 仅在模态框打开时加载
  )

  // 创建任务mutation
  const createMutation = useCreateCollectionTask()

  /**
   * 处理表单提交
   */
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields()

      await createMutation.mutateAsync({
        datasourceId: values.datasourceId,
        type: values.taskType, // 前端taskType映射到后端type字段
      })

      message.success('采集任务已创建,正在执行中...')
      form.resetFields()
      onClose()
    } catch (error) {
      console.error('Form validation failed:', error)
    }
  }

  /**
   * 处理取消
   */
  const handleCancel = () => {
    form.resetFields()
    onClose()
  }

  const datasources = datasourcesData?.content || []

  return (
    <Modal
      title="创建采集任务"
      open={open}
      onOk={handleSubmit}
      onCancel={handleCancel}
      confirmLoading={createMutation.isPending}
      okText="创建并启动"
      cancelText="取消"
      width={600}
    >
      <Form
        form={form}
        layout="vertical"
        initialValues={{
          taskType: TaskType.FULL,
        }}
      >
        <Form.Item
          name="datasourceId"
          label="选择数据源"
          rules={[
            { required: true, message: '请选择数据源' },
          ]}
        >
          <Select
            placeholder="请选择要采集的数据源"
            loading={loadingDatasources}
            showSearch
            optionFilterProp="children"
            filterOption={(input, option) =>
              (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
            }
            options={datasources.map((ds: DataSource) => ({
              label: `${ds.name} (${ds.host})`,
              value: ds.id,
            }))}
          />
        </Form.Item>

        <Form.Item
          name="taskType"
          label="采集类型"
          rules={[
            { required: true, message: '请选择采集类型' },
          ]}
        >
          <Radio.Group>
            <Radio.Button value={TaskType.FULL}>
              全量采集
              <span className="text-xs text-gray-500 ml-2">
                (采集所有表结构)
              </span>
            </Radio.Button>
            <Radio.Button value={TaskType.INCREMENTAL}>
              增量采集
              <span className="text-xs text-gray-500 ml-2">
                (仅采集变更的表)
              </span>
            </Radio.Button>
          </Radio.Group>
        </Form.Item>

        <div className="bg-blue-50 border border-blue-200 rounded p-3 mt-4">
          <p className="text-sm text-gray-700">
            <strong>说明:</strong>
          </p>
          <ul className="text-xs text-gray-600 list-disc list-inside mt-2 space-y-1">
            <li>全量采集: 采集数据源中的所有表结构,适用于首次采集或需要完整更新时</li>
            <li>增量采集: 仅采集有变更的表(基于SHA-256哈希对比),适用于日常更新</li>
            <li>任务创建后将立即开始执行,可在任务列表中查看进度</li>
          </ul>
        </div>
      </Form>
    </Modal>
  )
}

export default CreateTaskModal
